package com.zeratul.common.dubbo.plugin;

import com.zeratul.common.core.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.threadpool.ThreadPool;
import org.apache.dubbo.common.threadpool.support.fixed.FixedThreadPool;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_THREAD_NAME;
import static org.apache.dubbo.common.constants.CommonConstants.THREAD_NAME_KEY;

/**
 * 自定义Dubbo线程池插件，根据Spring的配置决定是否启用虚拟线程
 */
@Slf4j
public class AutoVirtualThreadPool implements ThreadPool {
    /**
     * Thread pool
     *
     * @param url URL contains thread parameter
     * @return thread pool
     */
    @SuppressWarnings("AlibabaThreadPoolCreation")
    @Override
    public Executor getExecutor(URL url) {
        //获取线程名称
        String name = url.getParameter(THREAD_NAME_KEY, (String) url.getAttribute(THREAD_NAME_KEY, DEFAULT_THREAD_NAME));

        //获取是否启用虚拟线程
        boolean virtual = SpringUtils.isVirtual();
        log.debug("【Dubbo线程池】是否开启虚拟线程：{}", virtual);
        if (virtual) {
            //如果是虚拟线程，则添加一个虚拟后缀
            name = name + "-virtual-";
            //返回虚拟线程
            return Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name(name, 1L).factory());
        }

        //返回默认线程池
        return new FixedThreadPool().getExecutor(url);
    }
}
